<template>
  <div class="approve-right-title">
    <el-text truncated>
      协同: {{ userTask.taskName }}
    </el-text>
  </div>
  <el-input v-show="!commentEditorFroala" v-model="completeTaskData.comment"
            placeholder="请输入评论" v-focus style="margin-top: 10px"
            :rows="6" type="textarea"></el-input>

  <div style="margin: 10px 0" class="approve-right-buttom-wrapper">
    <div class="left">
      <el-button size="small" icon="comment" @click="openFroala" round/>
      <el-button size="small" type="warning" icon="clear"
                 @click="clearComment" v-show="commentEditorFroala" round/>

      <el-dropdown trigger="click" v-show="!userTask.notify">
        <el-button style="margin-left: 10px" size="small" icon="more" round/>
        <template #dropdown>
          <el-dropdown-menu>
            <el-dropdown-item icon="add" @click="addUserSign">加签</el-dropdown-item>
            <el-dropdown-item icon="subtract" @click="removeCounterSign">减签</el-dropdown-item>
            <el-dropdown-item icon="notify" @click="informUsers">知会</el-dropdown-item>
            <el-dropdown-item icon="back" @click="toNode">指定回退</el-dropdown-item>
            <el-dropdown-item icon="edit" @click="editFlow">修改流程</el-dropdown-item>
            <el-dropdown-item icon="document" @click="editFlowDesc">修改附件</el-dropdown-item>
            <el-dropdown-item icon="transform" @click="changeUser">转办</el-dropdown-item>
          </el-dropdown-menu>
        </template>
      </el-dropdown>
    </div>

  </div>

  <FModal ref="commentModal" @ok="closeFroala" @cancel="closeFroala"
          header="请输入附言" width="1100">
    <froala id="edit" :tag="'textarea'" :config="froalaConfig"
            placeholder="请输入附言"
            v-model:value="completeTaskData.comment"></froala>
  </FModal>

  <FUploader ref="completeTaskDataUploader"/>

  <div style="margin-top: 10px; text-align: right">
    <el-button type="primary" :loading="loading" round @click="approveUserTask" icon="ok">同意</el-button>
    <el-button round style="margin-left: 10px" icon="close" :loading="loading"
               @click="toFormUserTask" v-show="!userTask.notify">退回</el-button>
    <el-button type="warning" round @click="end" :loading="loading"
               style="margin-left: 10px" icon="stop" v-show="!userTask.notify">结束
    </el-button>
  </div>
  <AddUserSignComponent :userTask="userTask"
                        ref="refAddUserSignComponent" @addUserSignOk="commentChange"/>

  <InformUserComponent :userTask="userTask"
                       ref="refInformUserComponent" @informUserOk="commentChange"/>

  <RemoveUserSignComponent :userTask="userTask"
                           ref="refRemoveUserSignComponent"/>

  <FlowApproveEditorComponent :formDefinition="formDefinition" @flowModelChange="flowModelChange"
                              ref="refFlowApproveEditorComponent"/>

  <FlowAttachEditorComponent @flowDescChange="flowDescChange" ref="refFlowAttachEditorComponent"/>

  <ChangeUserConponent ref="refChangeUserConponent" @userChange="userChange"/>

  <ToRollbackNodeComponent @toRollbackNode="toRollbackNode" ref="refToRollbackNodeComponent"/>
</template>

<script setup>
import {isEmpty} from '@/utils/CommonUtils';
import {getCurrentInstance, reactive, ref, shallowRef, toRaw} from 'vue';
import {ElMessageBox} from 'element-plus';
import FModal from '@/components/FModal/index.vue';
import FUploader from '@/components/FUploader/index.vue';
import {froalaConfig as _froalaConfig} from '@/components/MyFroala';
import UserTaskProcessHelper, {actionTypes} from '@/components/platwork/FormApproveComponent/UserTaskProcessHelper';
import './style.css';
import AddUserSignComponent from './AddUserSignComponent';
import InformUserComponent from './InformUserComponent';
import RemoveUserSignComponent from './RemoveUserSignComponent';
import FlowApproveEditorComponent from './FlowApproveEditorComponent';
import FlowAttachEditorComponent
  from '@/components/platwork/FormApproveComponent/ApproveComponent/FlowAttachEditorComponent';
import ChangeUserConponent from '@/components/platwork/FormApproveComponent/ApproveComponent/ChangeUserConponent';
import ToRollbackNodeComponent
  from '@/components/platwork/FormApproveComponent/ApproveComponent/ToRollbackNodeComponent';

defineOptions({
  name: 'ApproveComponent',
});

const internalInstance = getCurrentInstance();
const refAddUserSignComponent = shallowRef();
const refFlowApproveEditorComponent = shallowRef();
const refRemoveUserSignComponent = shallowRef();
const refInformUserComponent = shallowRef();
const refFlowAttachEditorComponent = shallowRef();
const refChangeUserConponent = shallowRef();
const refToRollbackNodeComponent = shallowRef();
const global = internalInstance.appContext.config.globalProperties;
const props = defineProps({
  getFormData: undefined,
  userTask: undefined,
  formFlowDesc: {
    attachmentIds: undefined,
    additionalComments: undefined,
    formDefinitionId: undefined,
    formName: undefined,
  },
  formDefinition: {
    form: {},
    formFields: []
  }
});
const loading = shallowRef(false);

const commentEditorFroala = shallowRef(false);
const completeTaskData = reactive({
  attachments: [],
  comment: undefined,
  commentAction: undefined,
  formData: undefined,
  commentActionInfo: undefined,
  userTaskId: undefined,
});
const commentModal = ref();
const froalaConfig = shallowRef({
  ..._froalaConfig,
  zIndex: 2008,
});
const completeTaskDataUploader = ref();

function clearComment() {
  ElMessageBox.confirm('清空后不可恢复', '清空评论?', {
    draggable: true,
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    commentEditorFroala.value = false;
    completeTaskData.comment = undefined;
  }).catch(() => {
  });
}

function closeFroala() {
  commentModal.value.close();
}

function openFroala() {
  commentEditorFroala.value = true;
  commentModal.value.open();
}

function getToFormCommentData() {
  let data = JSON.parse(JSON.stringify(toRaw(completeTaskData)));
  data.commentAction = actionTypes.toForm.type;
  data.commentActionInfo = actionTypes.toForm.name;
  data.userTaskId = props.userTask.id;
  data.attachmentIds = completeTaskDataUploader.value.getAttachmentIds();
  return data;
}

function getStopProcessCommentData() {
  let data = JSON.parse(JSON.stringify(toRaw(completeTaskData)));
  data.commentAction = actionTypes.end.type;
  data.commentActionInfo = actionTypes.end.name;
  data.userTaskId = props.userTask.id;
  data.attachmentIds = completeTaskDataUploader.value.getAttachmentIds();
  return data;
}

function getApproveCommentData() {
  let data = JSON.parse(JSON.stringify(toRaw(completeTaskData)));
  data.commentAction = actionTypes.approve.type;
  data.commentActionInfo = actionTypes.approve.name;
  data.userTaskId = props.userTask.id;
  data.attachmentIds = completeTaskDataUploader.value.getAttachmentIds();
  return data;
}

function getFlowDescChangeData(attachmentIds) {
  let data = JSON.parse(JSON.stringify(toRaw(props.formFlowDesc)));
  data.attachmentIds = attachmentIds;
  data.commentAction = actionTypes.attachmentEdit.type;
  data.commentActionInfo = actionTypes.attachmentEdit.name;
  data.userTaskId = props.userTask.id;
  data.comment = toRaw(completeTaskData).comment;
  return data;
}

function getFlowModelData(flowModel) {
  let data = JSON.parse(JSON.stringify(toRaw(completeTaskData)));
  data.commentAction = actionTypes.changeFlow.type;
  data.commentActionInfo = actionTypes.changeFlow.name;
  data.userTaskId = props.userTask.id;
  data.flowModel = JSON.stringify(flowModel);
  data.attachmentIds = completeTaskDataUploader.value.getAttachmentIds();
  return data;
}

function getUserChangeData(user, realname) {
  let data = JSON.parse(JSON.stringify(toRaw(completeTaskData)));
  data.commentAction = actionTypes.changeUser.type;
  data.commentActionInfo = actionTypes.changeUser.name;
  data.userTaskId = props.userTask.id;
  data.user = user;
  data.realname = realname;
  data.attachmentIds = completeTaskDataUploader.value.getAttachmentIds();
  return data;
}

function getRollbackNodeData(rollbackNodeId) {
  let data = JSON.parse(JSON.stringify(toRaw(completeTaskData)));
  data.commentAction = actionTypes.toRollbackNode.type;
  data.commentActionInfo = actionTypes.toRollbackNode.name;
  data.userTaskId = props.userTask.id;
  data.rollbackNodeId = rollbackNodeId;
  data.attachmentIds = completeTaskDataUploader.value.getAttachmentIds();
  return data;
}


function createApproveData(formData) {
  let data = getApproveCommentData();
  data.formData = JSON.parse(JSON.stringify(formData));
  return data;
}

function toFormUserTask() {
  loading.value = true;
  let commentData = getToFormCommentData();
  UserTaskProcessHelper.toFormUserTask(commentData).then(global.$windowManager.close);
}

function approveUserTask() {
  if (isEmpty(props.getFormData)) return;

  loading.value = true;
  props.getFormData().then(formData => {
    let data = createApproveData(formData);
    UserTaskProcessHelper.approve(data).then(global.$windowManager.close);
  }).catch(e => {
    loading.value = false;
  })
}

function end() {
  loading.value = true;
  let data = getStopProcessCommentData();
  UserTaskProcessHelper.end(data).then(global.$windowManager.close);
}

function commentChange() {
  ElMessageBox.confirm('当前审批历史已更新, 是否重新加载页面? ', '是否重新加载页面?', {
    draggable: true,
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    window.location.reload();
  }).catch(() => {
  });
}

function flowModelChange(flowModel, before) {
  let data = getFlowModelData(flowModel);
  UserTaskProcessHelper.changeFlow(data, before).then(() => {
    ElMessageBox.alert('流程修改后需要刷新当前页面', '页面即将刷新', {
      autofocus: true,
      callback: () => {
        window.location.reload();
      }
    });
  });
}

function flowDescChange(attachmentIds) {
  let data = getFlowDescChangeData(attachmentIds);
  UserTaskProcessHelper.flowDescChange(data).then(() => {
    ElMessageBox.alert('修改后需要刷新当前页面', '页面即将刷新', {
      autofocus: true,
      callback: () => {
        window.location.reload();
      }
    });
  });
}

function userChange(user, realname) {
  let data = getUserChangeData(user, realname);
  UserTaskProcessHelper.userChange(data).then(global.$windowManager.close);
}

function toRollbackNode(rollbackNodeId) {
  let data = getRollbackNodeData(rollbackNodeId);
  UserTaskProcessHelper.toRollbackNode(data).then(global.$windowManager.close);
}

function getChangeUserData() {

}

function editFlowDesc() {
  refFlowAttachEditorComponent.value.setData(props.formFlowDesc);
}

function changeUser() {
  refChangeUserConponent.value.setData();
}

function informUsers() {
  refInformUserComponent.value.setData();
}

function addUserSign() {
  refAddUserSignComponent.value.setData();
}

function removeCounterSign() {
  refRemoveUserSignComponent.value.setData();
}

function editFlow() {
  refFlowApproveEditorComponent.value.setData(props.userTask.processInstanceId);
}

function toNode() {
  refToRollbackNodeComponent.value.setData(props.userTask);
}
</script>
